<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>多点标记</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
	<div id="map"></div>

    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCqsn1M2pSssz9OrldUVHP4ELTDToelVYw" defer></script>
	<script>
		let uluru;
		let zoom = 15; // 数字越大，高度越低
		let map;
		let arr = [];
		let num = 1;
		let markers = [];
		let markersArray = {};
		let position = [];

		// 根据网络定位
		var geolocation = 'https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyCqsn1M2pSssz9OrldUVHP4ELTDToelVYw';
		(function() {
		    xhr = new XMLHttpRequest();
		    xhr.open('POST', geolocation);
		    xhr.onload = function () {
		        var response = JSON.parse(this.responseText);
		        uluru = response.location; // 获取经纬度
		        initMap(uluru); // 调用地图
		    }
		    xhr.send();
		})();

		// 地图
		function initMap(uluru) {
			map = new google.maps.Map(document.getElementById("map"), {
				center: uluru,
				zoom: zoom 
			});

			// 点击获取对应google地图上的坐标
			google.maps.event.addListener(map, 'click', function (event) {
				// position.push(event.latLng);
				var obj = {};
				// 把坐标存入对象
				obj.lat = event.latLng.lat();
				obj.lng = event.latLng.lng();
				// 存入多变形数组中
				position.push(obj);
				clearMarker();
				for (var i = 0; i < position.length; i++) {
				    addMarker(i);
				}
			});
		};


		// 多点标记
		function addMarker(e) {
			markers[e] = new google.maps.Marker({
				position: {
					lat: position[e].lat,
					lng: position[e].lng
				},
				map: map,
				label: position[e].label
			});
		}

		//删除标注
		function clearMarker() {
			for (var i = 0; i < markers.length; i++) {
				markers[i].setMap(null);
			}

			markers = [];
		}

		window.onload = function() {
    		initMap();
		}
	</script>
</body>
</html>